/**
 * @PlayMovie.as
 * 
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2010 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:挂机冒险
 * <br>Date:2014-6-18
 */
package com.asframe.display.movie
{
	import com.asframe.collections.maps.HashMap;
	import com.asframe.tick.Tick;
	import com.asframe.utils.FunctionUtils;
	
	import flash.display.MovieClip;
	import flash.events.Event;

	/**
	 * 播放影片剪辑
	 * @author sodaChen
	 * Date:2014-6-18
	 */
	public class PlayMovie
	{
		private static var movieList:Vector.<MovieData> = new Vector.<MovieData>();
		private static var movieMap:HashMap = new HashMap();
		public static function playMovie(movie:MovieClip,callBack:Function = null,param:Object = null,isEvent:Boolean = false):void
		{
			var movieData:MovieData = new MovieData();
			movieData.movie = movie;
			movieData.callBack = callBack;
			movieData.param = param;
			movieData.isEvent = isEvent;
			if(isEvent)
			{
				movieMap.put(movie,movieData);
				movie.addEventListener(Event.COMPLETE,onComplete);
				movie.gotoAndPlay(1);
			}
			else
			{
				movie.gotoAndStop(1);
				movieList.push(movieData);
				if(movieList.length == 1)
					Tick.addFun(tick);
			}
		}
		private static function onComplete(evt:Event):void
		{
			var movieData:MovieData = movieMap.remove(evt.currentTarget);
			var movie:MovieClip = movieData.movie;
			movie.stop();
			if(movie.parent != null)
				movie.parent.removeChild(movie);
			FunctionUtils.executeParam(movieData.callBack,movieData.param);
		}
		private static function closeMovie(movie:MovieClip):void
		{
			movieMap.remove(movie);
			movie.stop();
			if(movie.parent != null)
				movie.parent.removeChild(movie);
		}
		private static function tick():void
		{
			var len:int = movieList.length;
			var movie:MovieClip = null;
			var movieData:MovieData = null;
			for (var i:int = 0; i < len; i++) 
			{
				movieData = movieList[i];
				movie = movieData.movie;
				if(movie.currentFrame == movie.totalFrames)
				{
					//进行删除
					movieList.splice(i,1);
					i--;
					len--;
					if(len == 0)
						Tick.removeFun(tick);
					
					if(movieData.callBack != null)
						FunctionUtils.executeParam(movieData.callBack,movieData.param);
					else
						closeMovie(movie);
				}
				else
				{
					movie.nextFrame();
				}
			}
		}
	}
}